// pages/circle_photos/index.js
var common = require('../../lib/common.js');
var url = require('../../config/url.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    // 选项
    options: {
      nav: [],
      active: 0,
      page: [],
      photos: [],
      loadding: [],
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ id: options.id });
    this.getPhotoType();
  },

  /**
   * 获取相册分类
   */
  getPhotoType() {
    common.post(url.getCirclePhotoTypeList, { circle_id: this.data.id }, (data) => {
      let options = {};
      options.nav = [{
        id: 0,
        name: '全部'
      }];
      options.page = [1];
      options.photos = [[]];
      options.loadding = [false];
      options.active = 0;
      for (let i in data) {
        options.nav.push({ id: data[i].id, name: data[i].name });
        options.photos.push([]);
        options.page.push(1);
        options.loadding.push(false);
      }

      this.setData({ options });
      this.loadPhoto(0);
    })
  },

  onOptionChange({ detail }) {
    let options = this.data.options;
    options.active = detail.index;
    this.setData({ options });

    if (options.page[detail.index] > 1 || options.page[detail.index] === false) {
      return;
    }
    this.loadPhoto(detail.index);
  },

  loadPhoto(index) {
    let options = this.data.options;
    if (options.loadding[index]) return;
    options.loadding[index] = true;
    this.setData({ options });

    let complete = (data) => {
      let options = this.data.options;
      options.loadding[index] = false;
      options.photos[index] = options.photos[index].concat(data);
      options.page[index]++;

      if (data.length == 0)
        options.page[index] = false;
      this.setData({ options });
    }

    if (index == 0) {
      this.getNewList(index, complete);
    } else {
      this.getByTypeList(index, complete);
    }
  },

  /**
     * 获取最新照片列表
     */
  getNewList(index, complete) {
    common.post(url.getCirclePhotoNewList, { circle_id: this.data.id, page: this.data.options.page[index], limit: 10 }, (data) => {
      for (let i in data) {
        data[i].url = '/pages/circle_photos_detail/index?id=' + data[i].id;
      }
      if (complete)
        complete(data);
    })
  },

  /**
   * 根据类型获取
   * @param {*} index 
   * @param {*} complete 
   */
  getByTypeList(index, complete) {
    let id = this.data.options.nav[index].id;
    common.post(url.getCirclePhotoList, { circle_photo_type_id: id, page: this.data.options.page[index] }, (data) => {
      for (let i in data) {
        data[i].url = '/pages/circle_photos_detail/index?id=' + data[i].id;
      }
      if (complete)
        complete(data);
    })
  },

  onReachBottom() {
    let options = this.data.options;
    if (options.page[options.active] === false) {
      return;
    }
    console.log(options);
    this.loadPhoto(options.active);
  },

})